package cn.com.shbs.Controller;


import cn.com.shbs.Config.CommonUtil;
import cn.com.shbs.Config.Page;
import cn.com.shbs.Config.PasswordHelper;
import cn.com.shbs.Dao.LoginUserDao.LoginUserDao;
import cn.com.shbs.Dao.StoreRole.StoreRoleDao;
import cn.com.shbs.Dao.UserInfoDao.UserInfoDao;
import cn.com.shbs.Dao.UserInfoDao.UserInfoDao;
import cn.com.shbs.Service.UserInfoService.IUserInfoService;
import cn.com.shbs.Service.code.SerialNumberGeneratorService;
import cn.com.shbs.model.LoginUser;
import cn.com.shbs.model.Store;
import cn.com.shbs.model.StoreRole;
import cn.com.shbs.model.UserInfo.UserInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;


@RestController
public class UserInfoController {

    static Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    @Autowired
    LoginUserDao loginUserDao;
    
    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    SerialNumberGeneratorService serialNumberGeneratorService;

    @Autowired
    IUserInfoService userInfoService;

    StoreRoleDao StoreRoleDao;

    /**
     * 添加用户
     * @return
     */
    @RequestMapping(value = "API/adduserinfo",method = RequestMethod.POST)
    public Object adduserinfo(HttpServletRequest request, LoginUser userInfo){

        String message="error";
        JSONObject result=new JSONObject();

        try {
            LoginUser us=null;
            //根据登录名查询是否唯一
             us =  loginUserDao.findByloginname(userInfo.getLogin_name());
            if (us!=null){
                message="nameexit";
                result.put("message",message);
                return result;
            }

            PasswordHelper helper=new PasswordHelper();
            helper.encryptPassword(userInfo);
            byte State = 0;
            //userInfo.setCreattime(CommonUtil.getNowTime_tamp());
            String user_code=  CommonUtil.PREFIX_SYSUSER+serialNumberGeneratorService.getCodeGeneratorstr(CommonUtil.STEPNUM,CommonUtil.SYSUSER_TYPE);
            userInfo.setUser_code(user_code);
            //userInfo.setCreatid(userInfo.getUid());
            userInfoService.Modfiysysuser(userInfo);
            message="success";

        }catch (Exception e){
            logger.error("UserInfoController.addsysuser()",e);
            e.printStackTrace();
        }

        result.put("message",message);
        return result.toString();
    }


    /**
     * 登陆
     * @param request
     * @param loginname 登陆用户名
     * @param password 密码
     * @param remberMe 是否记住
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Object loginaction(javax.servlet.http.HttpServletRequest request,
                              String loginname,
                              String password,
                              String remberMe){
        String message="success";
        JSONObject result=new JSONObject();
        try {
            Subject sub = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(loginname,password);
            if ("true".equals(remberMe)){
                token.setRememberMe(true);
            }else {
                token.setRememberMe(false);
            }
            try {
                sub.login(token);
                Subject subject = SecurityUtils.getSubject();
                //取身份信息
                LoginUser userInfo = (LoginUser) subject.getPrincipal();
                StoreRole role=null;
                if(userInfo.getStore_role_code()!=null&&!"".equals(userInfo.getStore_role_code().trim())){
                    role= StoreRoleDao.queryStoreRole(userInfo.getStore_role_code());


                }

                JSONObject userjson=JSONObject.fromObject(userInfo);
                JSONObject rolejson=JSONObject.fromObject(role);

                message="success";
                result.put("userinfo",userjson);
                result.put("role",rolejson);

            }catch (AuthenticationException e){
                if (UnknownAccountException.class.getName().equals(e.getClass().getName())) {

                    message="nameerror";
                } else if (IncorrectCredentialsException.class.getName().equals(e.getClass().getName())) {
                    message="passerror";

                } else {
                    message="error";

                }

            }


        }catch (Exception e){
            message="error";
            logger.error("UserInfoController.loginaction()",e);
        }
        result.put("message",message);
        return result.toString();
    }
    
    /**
	 * 通过店铺ID查用户表
	 * @param request
	 * @param response
	 * @param store_code
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/FindUserInfoByStoreId")
	public Object FindUserInfoByStoreId(HttpServletRequest request, HttpServletResponse response,
			 String store_code,
			 Page page
			) throws Exception {
		
		
		logger.info("UserInfoController.FindShopByName()方法开始");
		
		String message = "success";
		JSONObject result=new JSONObject();
		
		
		HashMap map=new HashMap();
		List<UserInfo>  loginUsers_list = new ArrayList<UserInfo>();
		

		try {
			
			int total=userInfoDao.FindUserInfoByStoreIdNums(store_code);
			page.setTotalCount(total);
			map.put("pagestart", page.getStartCount());
			map.put("limit",page.getPageSize());
			map.put("store_code",store_code);
			
			loginUsers_list =	userInfoDao.FindUserInfoByStoreId(map);
		
			message = "success";
			
		} catch (Exception e) {
			logger.error("UserInfoController.FindShopByName()方法异常", e);
			message = "error";
			e.printStackTrace();
		}
		
		result.put("message",message);
		result.put("Userlist",loginUsers_list);
		result.put("page", page);
	     return result.toString();

	}
    

    @RequestMapping( {"/getloginUser"})
    public Object getloginUser(javax.servlet.http.HttpServletRequest request){

        String message="nouser";

        JSONObject result=new JSONObject();
        try {
            Subject subject = SecurityUtils.getSubject();
            //取身份信息
            LoginUser userInfo = (LoginUser) subject.getPrincipal();
            HashMap map=new HashMap();

            StoreRole role=null;
            if(userInfo.getStore_role_code()!=null&&"".trim().equals(userInfo.getStore_role_code())){
                role= StoreRoleDao.queryStoreRole(userInfo.getStore_role_code());


            }
            JSONObject userjson=JSONObject.fromObject(userInfo);
            JSONObject rolejson=JSONObject.fromObject(role);
            message="success";

            result.put("userinfo",userjson);
            result.put("role",rolejson);


        }catch (Exception e){
            logger.error("sysUserController.getloginUser()",e);
        }



        result.put("message",message);

        return result.toString();
    }

}
